//
//  PPEditPetInfoTableViewController.m
//  pet
//
//  Created by 陈无忌 on 11/21/14.
//  Copyright (c) 2014 whalefin. All rights reserved.
//

#import "PPEditPetInfoTableViewController.h"
#import "PPEditPetPhotoViewController.h"
#import "PPBLEDeviceTableViewController.h"
#import "QRCodeGenerator.h"
#import "PPZBarViewController.h"
#import "PPPetPhotoCollectionViewCell.h"
#import "supportingHeadFiles.h"
#import "PPCameraAuthorization.h"
#import "PPAppDelegate.h"


@interface PPEditPetInfoTableViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIPickerViewDataSource,UIPickerViewDelegate,UITextFieldDelegate,UIActionSheetDelegate,UITextViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource,ScanQRCodeDelegate>
@property (weak, nonatomic) PPSystemConfiguraton *config;

@property (weak, nonatomic) IBOutlet UIImageView *petAvatarImageView;

@property (weak, nonatomic) IBOutlet UITextField *petNameTF;
@property (weak, nonatomic) IBOutlet UITextField *petAgeTF;
@property (weak, nonatomic) IBOutlet UITextField *petBreedTF;
@property (weak, nonatomic) IBOutlet UITextField *petLengthTF;
@property (weak, nonatomic) IBOutlet UITextField *petWeightTF;
@property (weak, nonatomic) IBOutlet UITextField *petColorTF;
@property (weak, nonatomic) IBOutlet UITextView *introductionTextView;
@property (weak, nonatomic) IBOutlet UILabel *optionLabel;

@property (weak, nonatomic) IBOutlet UISegmentedControl *breedingSC;
@property (weak, nonatomic) IBOutlet UIButton *choseMaleButton;
@property (weak, nonatomic) IBOutlet UIButton *choseFemaleButton;

@property (weak, nonatomic) IBOutlet UICollectionView *petPhotoCollectionView;
@property (weak, nonatomic) IBOutlet UILabel *petPhotoLabel;
@property (weak, nonatomic) IBOutlet UILabel *petQRCodeLabel;


@property (nonatomic) int gender;
@property (nonatomic, strong) NSString *petBreed;
@property (nonatomic, strong) NSString *petType;
@property (nonatomic, strong) NSArray *petBreedArray;
@property (nonatomic, strong) NSArray *petTypeArray;
@property (nonatomic, strong) NSString *filePath;

@property (nonatomic, strong) UIPickerView *petPickerView;
@property (strong, nonatomic) UIToolbar *toolBar;
@property (strong, nonatomic) UIBarButtonItem *cancelButton;
@property (strong, nonatomic) UIBarButtonItem *doneButton;

@property (strong, nonatomic) UIImagePickerController *imagePicker;

@property (strong, nonatomic) UIDatePicker *datePicker;
@property (nonatomic, strong) UIToolbar *dateToolBar;
@property (nonatomic, strong) UIBarButtonItem *dateDoneButton;
@property (nonatomic, strong) UIBarButtonItem *dateCancelButton;
@property (nonatomic, strong) NSDateFormatter *formatter;

@property (nonatomic) CGFloat photoCellHeight;

@property (nonatomic, strong) MBProgressHUD *hud;

@end

@implementation PPEditPetInfoTableViewController

//date picker view
- (NSDateFormatter *)formatter
{
    if (!_formatter) {
        _formatter = [[NSDateFormatter alloc] init];
        NSTimeZone *timeZone = [NSTimeZone localTimeZone];
        [_formatter setTimeZone:timeZone];
        [_formatter setDateFormat:@"yyyy/MM/dd"];
    }
    return _formatter;
}
//UIDatePicker
- (UIDatePicker *)datePicker
{
    if (!_datePicker) {
        _datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 0, 320, 260)];
    }
    return _datePicker;
}
- (UIToolbar *)dateToolBar
{
    if (!_dateToolBar) {
        _dateToolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
        UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
        NSArray *toolBarItems = [[NSArray alloc] initWithObjects:self.dateCancelButton, space, self.dateDoneButton, nil];
        [_dateToolBar setItems:toolBarItems];
    }
    return _dateToolBar;
}
- (UIBarButtonItem *)dateCancelButton
{
    if (!_dateCancelButton) {
        _dateCancelButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelDateButtonPressed:)];
    }
    return _dateCancelButton;
}
- (UIBarButtonItem *)dateDoneButton
{
    if (!_dateDoneButton) {
        _dateDoneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneDateButtonPressed:)];
    }
    return _dateDoneButton;
}

- (void)cancelDateButtonPressed:(UIBarButtonItem *)sender
{
    if ([self.petAgeTF isFirstResponder]) {
        [self.petAgeTF resignFirstResponder];
    }
}
- (void)doneDateButtonPressed:(UIBarButtonItem *)sender
{
    if ([self.petAgeTF isFirstResponder]) {
        [self.petAgeTF resignFirstResponder];
        self.petAgeTF.text = [self.formatter stringFromDate:self.datePicker.date];
    }
}

- (UIImagePickerController *)imagePicker
{
    if (!_imagePicker) {
        _imagePicker = [[UIImagePickerController alloc] init];
        
        _imagePicker.allowsEditing = YES;
        _imagePicker.delegate = self;
    }
    return _imagePicker;
}

-(PPSystemConfiguraton *)config{
    if (!_config) {
        _config = [PPSystemConfiguraton sharedSystemConfiguration];
    }
    return _config;
}

-(UIPickerView *)petPickerView
{
    if (!_petPickerView) {
        _petPickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 0, 320, 260)];
        _petPickerView.delegate = self;
        _petPickerView.dataSource = self;
    }
    return _petPickerView;
}
-(UIToolbar *)toolBar
{
    if (!_toolBar) {
        _toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
        UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
        NSArray *toolBarItems = [[NSArray alloc] initWithObjects:self.cancelButton, space, self.doneButton, nil];
        [_toolBar setItems:toolBarItems];
    }
    return _toolBar;
}
- (UIBarButtonItem *)cancelButton
{
    if (!_cancelButton) {
        _cancelButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelButtonPressed:)];
    }
    return _cancelButton;
}
- (UIBarButtonItem *)doneButton
{
    if (!_doneButton) {
        _doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneButtonPressed:)];
    }
    return _doneButton;
}

- (void)cancelButtonPressed:(UIBarButtonItem *)sender
{
    if ([self.petBreedTF isFirstResponder]) {
        [self.petBreedTF resignFirstResponder];
    }
    
}
- (void)doneButtonPressed:(UIBarButtonItem *)sender
{
    if ([self.petBreedTF isFirstResponder]) {
        [self.petBreedTF resignFirstResponder];
        
        self.petType = [self.petTypeArray objectAtIndex:[self.petPickerView selectedRowInComponent:0]];
        self.petBreed = [self.petBreedArray objectAtIndex:[self.petPickerView selectedRowInComponent:1]];
        self.petBreedTF.text = self.petBreed;
    }
}

-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.choseMaleButton addTarget:self action:@selector(choseMale:) forControlEvents:UIControlEventTouchUpInside];
    [self.choseFemaleButton addTarget:self action:@selector(choseFemale:) forControlEvents:UIControlEventTouchUpInside];
    self.choseMaleButton.tag = 0;
    self.choseFemaleButton.tag = 1;
    
    self.petTypeArray = [PPPetTypeArrayList getType];
    self.petBreedArray = [PPPetTypeArrayList getBreedWithType:[NSString stringWithFormat:@"%@",self.petTypeArray.firstObject]];
    
    self.petPhotoCollectionView.delegate = self;
    self.petPhotoCollectionView.dataSource = self;
    
    self.petType = self.pet.petType;
    self.petBreed = self.pet.petBreed;
    
    self.petNameTF.delegate = self;
    self.petAgeTF.delegate = self;
    self.petBreedTF.delegate = self;
    self.petLengthTF.delegate = self;
    self.petWeightTF.delegate = self;
    self.petColorTF.delegate = self;
    self.introductionTextView.delegate = self;
    
    UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(chooseImage)];
    recognizer.numberOfTouchesRequired = 1;
    recognizer.numberOfTapsRequired = 1;
    self.petAvatarImageView.userInteractionEnabled = YES;
    [self.petAvatarImageView addGestureRecognizer:recognizer];
    
    self.petBreedTF.inputView = self.petPickerView;
    self.petBreedTF.inputAccessoryView = self.toolBar;
    
    
    self.petAgeTF.inputView = self.datePicker;
    self.petAgeTF.inputAccessoryView = self.dateToolBar;
    [self dataSet];
    [self codeLabelSet];
}

-(void)chooseImage
{
    UIActionSheet *choiceSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"拍照", @"从相册中选取", nil];
    [choiceSheet showInView:self.tableView];
}


- (void)codeLabelSet
{
    if (self.pet.code.length > 0) {
        self.petQRCodeLabel.text = @"宠物身份证（已绑定）";
    }else{
        self.petQRCodeLabel.text = @"宠物身份证（未绑定）";
    }
}

- (void)dataSet
{
    [self.petAvatarImageView setImageWithURL:[PPImageUrl getImageUrl:self.pet.petAvatar] placeholderImage:[UIImage imageNamed:@"defaultAvatar"] usingActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    self.petNameTF.text = self.pet.petName;
    self.petAgeTF.text = self.pet.birth;
    self.petBreedTF.text = self.petBreed;
    if ([self.pet.breeding isEqualToString:@"yes"]) {
        [self.breedingSC setSelectedSegmentIndex:0];
        self.photoCellHeight = 70;
        self.petPhotoCollectionView.hidden = NO;
        self.petPhotoLabel.hidden = NO;
    }else{
        [self.breedingSC setSelectedSegmentIndex:1];
        self.photoCellHeight = 0;
        self.petPhotoCollectionView.hidden = YES;
        self.petPhotoLabel.hidden = YES;
    }
    switch (self.pet.petGender) {
        case 0:
            [self.choseMaleButton setImage:[UIImage imageNamed:@"maleBig"] forState:UIControlStateNormal];
            [self.choseFemaleButton setImage:[UIImage imageNamed:@"female"] forState:UIControlStateNormal];
            self.gender = 0;
            break;
        case 1:
            [self.choseMaleButton setImage:[UIImage imageNamed:@"male"] forState:UIControlStateNormal];
            [self.choseFemaleButton setImage:[UIImage imageNamed:@"femaleBig"] forState:UIControlStateNormal];
            self.gender = 1;
            break;
        default:
            break;
    }
    if (self.pet.petLong) {
        self.petLengthTF.text = [NSString stringWithFormat:@"%.2f",self.pet.petLong];
    }else{
        self.petLengthTF.text = @"";
    }
    
    if (self.pet.weight) {
        self.petWeightTF.text = [NSString stringWithFormat:@"%.2f",self.pet.weight];
    }else{
        self.petWeightTF.text = @"";
    }
    
    if (self.pet.color.length > 0 && self.pet.color) {
        self.petColorTF.text = self.pet.color;
    }else{
        self.petColorTF.text = @"";
    }
    if (self.pet.introduction.length > 0 && self.pet.introduction) {
        self.introductionTextView.text = self.pet.introduction;
        self.optionLabel.hidden = YES;
    }else{
        self.optionLabel.hidden = NO;
    }
    
    [self.tableView reloadData];
    [self.petPhotoCollectionView reloadData];

   

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source


#pragma mark - Table view delegate
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 88;
    }else if (indexPath.row == 5 && indexPath.section == 1){
        return self.photoCellHeight;
    }else if (indexPath.row == 6 && indexPath.section == 1){
        return 88;
    }else {
        return 44;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 5 && indexPath.section == 1) {
        PPEditPetPhotoViewController *targetVC = [self.storyboard instantiateViewControllerWithIdentifier:@"PPPetPhotoViewController"];
        targetVC.pet = self.pet;
        [self.navigationController pushViewController:targetVC animated:YES];
    }else if (indexPath.row == 1 && indexPath.section == 3) {
        if (!IS_OS_7_OR_LATER) {
            [UIAlertView showWithTitle:@"设备不支持" message:@"必须升级到iOS7以支持蓝牙狗牌" cancelButtonTitle:@"确定" otherButtonTitles:nil tapBlock:nil];
        } else {
            PPBLEDeviceTableViewController *targetVC = [[UIStoryboard storyboardWithName:@"BlueToothSetting" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"PPBLEDeviceTableViewController"];
            [self.navigationController pushViewController:targetVC animated:YES];
        }
    }else if (indexPath.row == 0 && indexPath.section == 3){
        PPZBarViewController *targetVC = [self.storyboard instantiateViewControllerWithIdentifier:@"zbarVC"];
        targetVC.delegate = self;
        [self.navigationController pushViewController:targetVC animated:YES];
    }

}
#pragma mark - Scan

- (void)scanFinishedWithResult:(NSString *)resultString
{
    NSString *url = [PPAPIList getAPIList].PPUpdatePetCodeById;
    
    NSString *prefix = @"http://sfz.fundoing.cn/pet/info?id=";
    
    NSString *petCode;
    
    if ([resultString hasPrefix:prefix]) {
        petCode = [resultString substringFromIndex:35];
    }
    
    if (petCode) {
        NSDictionary *params = @{@"petId":@(self.pet.id),@"code":petCode};
        [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation,id responseObject){
            NSLog(@"%@",responseObject);
            NSNumber *processResult = responseObject[@"processResult"];
            if (processResult.integerValue == 1) {
                [UIAlertView showWithTitle:@"绑定成功" message:@"宠物二维码成功绑定" cancelButtonTitle:@"确定" otherButtonTitles:nil tapBlock:nil];
                self.petQRCodeLabel.text = @"宠物身份证（已绑定）";
            }
        }failure:^(AFHTTPRequestOperation *operation, NSError *error){
            NSLog(@"%@",error);
        }];
    } else {
        [UIAlertView showWithTitle:@"无效二维码" message:@"请确保二维码为宠缘提供的有效二维码" cancelButtonTitle:@"确定" otherButtonTitles:nil tapBlock:nil];
    }
}

#pragma mark - Collection view data source
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (self.pet.petImgList.count > 0) {
//        return self.pet.petImgList.count;
        return 3;
    }else{
        return 0;
    }
}



- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    PPPetPhotoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"petPhotoCell" forIndexPath:indexPath];
    PPPetPhoto *photo = [self.pet.petImgList objectAtIndex:indexPath.row];
    [cell.photoView setImageWithURL:[PPImageUrl getImageUrl:photo.img] placeholderImage:[UIImage imageNamed:@"defaultImage"] usingActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    [cell.photoView setContentMode:UIViewContentModeScaleAspectFill];
    [cell.photoView setClipsToBounds:YES];
    return cell;
}



#pragma mark - Pick view data soure
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView//返回选择器组件数
{
    //    if ([pickerView isEqual:self.petPickerView])
    return 2;
    
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component//选择器的选项个数
{
    //    if ([pickerView isEqual:self.petPickerView])
    if (component == 0) {
        return self.petTypeArray.count;
    }else{
        return self.petBreedArray.count;
    }
}

-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    if (component == 0) {
        UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 160, 44)];
        UILabel *myLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 160, 44)];
        [myLabel setText:[self.petTypeArray objectAtIndex:row]];
        myLabel.textAlignment = NSTextAlignmentCenter;
        myLabel.Font = [UIFont fontWithName:@"Arial" size:14];
        [myView addSubview:myLabel];
        return myView;
    }else{
        UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 160, 44)];
        UILabel *myLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 160, 44)];
        [myLabel setText:[self.petBreedArray objectAtIndex:row]];
        myLabel.textAlignment = NSTextAlignmentCenter;
        myLabel.Font = [UIFont fontWithName:@"Arial" size:14];
        [myView addSubview:myLabel];
        return myView;
    }
}

- (void)pickerView:(UIPickerView *)pickerView
      didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    if (component == 0) {
        self.petBreedArray = [PPPetTypeArrayList getBreedWithType:[NSString stringWithFormat:@"%@",[self.petTypeArray objectAtIndex:row]]];
        [self.petPickerView reloadComponent:1];
    }
}

#pragma mark - ActionSheet
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 2) {
        return;
    }else if (buttonIndex == 1) {
        self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }else if (buttonIndex == 0){
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            if (IS_OS_7_OR_LATER) {
                [PPCameraAuthorization getCameraAuthorization];
                if (!self.config.isCameraValid) {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"请在iPhone的“设置-隐私-相机”选项中，允许程序访问你的相机" delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil];
                    [alert show];
                    return;
                }else{
                    [self.imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
                }
            }else{
                [self.imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
            }

        }else{
            [self.imagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
            
        }
    }
    [self presentViewController:self.imagePicker animated:YES completion:nil];
}

#pragma mark - UIImagePickContrillerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info valueForKey:UIImagePickerControllerEditedImage];
    [self.petAvatarImageView setImage:image];
    self.filePath = [self uploadUserAvatar:self.petAvatarImageView.image];
    image = nil;
    [self.imagePicker dismissViewControllerAnimated:YES completion:^{
        [HUD showUIBlockingIndicatorWithText:@"正在上传宠物头像"];
        NSString *url = [PPAPIList getAPIList].PPSaveOrUpdatePetMsg;
        NSDictionary *params =@{@"userId":@(self.config.userInfo.id),
                                @"petId":@(self.pet.id)};
        [httpRequst POST:url parameters:params imagePath:self.filePath imageName:@"petAvatar" keyWords:@"petAvatar" success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            NSLog(@"%@",responseObject);
            NSNumber *processResult = responseObject[@"processResult"];
            if (processResult.intValue == 1) {
                [HUD hideUIBlockingIndicator];
                [self alertShow:@"宠物头像上传成功"];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"reload" object:nil];
                
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"%@",error);
            [HUD hideUIBlockingIndicator];
        }];
    }];
}

//将图片存至本地沙箱 并获得图片的存储路径
- (NSString *)uploadUserAvatar:(UIImage *)image
{
    NSData *data;
    if (UIImagePNGRepresentation(image).length > 2100000) {
        data = UIImageJPEGRepresentation(image, 0.5);
    }else{
        data = UIImagePNGRepresentation(image);
    }
    //图片保存的路径
    //这里将图片放在沙盒的documents文件夹中
    NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    //文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //把刚刚图片转换的data对象拷贝至沙盒中 并保存为image.png
    [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
    [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/petAvatar.png"] contents:data attributes:nil];
    //得到选择后沙盒中图片的完整路径
    return [[NSString alloc]initWithFormat:@"%@%@",DocumentsPath,  @"/petAvatar.png"];
}


#pragma mark - Custom IBAction
- (IBAction)setBreed:(UISegmentedControl *)sender {
    if (sender.selectedSegmentIndex == 0) {
        //选择需要配种 显示相册
        if (!(self.pet.petImgList.count > 0)) {
            //没有宠物提示添加
           [UIAlertView showWithTitle:@"提示" message:@"开启宠物配种需要添加宠物相册，您还没添加" cancelButtonTitle:@"返回" otherButtonTitles:@[@"现在就去"] tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
                if (buttonIndex == 1) {
                    //去宠物相册页
                    PPEditPetPhotoViewController *targetVC = [self.storyboard instantiateViewControllerWithIdentifier:@"PPPetPhotoViewController"];
                    targetVC.pet = self.pet;
                    [self.navigationController pushViewController:targetVC animated:YES];
                }else{
                    sender.selectedSegmentIndex = 1;
                }
           }];
        }else{
            NSMutableArray *indexPaths = [NSMutableArray array];
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:6 inSection:0];
            [indexPaths addObject:indexPath];
            self.photoCellHeight = 70;
            self.petPhotoCollectionView.hidden = NO;
            self.petPhotoLabel.hidden = NO;
            [self.tableView reloadData];
        }
    }else{
        self.photoCellHeight = 0;
        self.petPhotoCollectionView.hidden = YES;
        self.petPhotoLabel.hidden = YES;
        [self.tableView reloadData];
    }
}

-(void) alertShow:(NSString *)msg
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
    [alert show];
}

- (IBAction)save:(id)sender {
    //end edit & send to service
    //check
    if (!self.petNameTF.text.length > 0) {
        [self alertShow:@"请填写宠物的名字！"];
        return;
    }
    if (!self.petAgeTF.text.length > 0) {
        [self alertShow:@"请填写宠物的生日！"];
        return;
    }
    if (!self.petBreedTF.text.length > 0) {
        [self alertShow:@"请填写宠物的品种！"];
        return;
    }
    [HUD showUIBlockingIndicatorWithText:@"正在保存"];
    NSString *breeding;
    switch (self.breedingSC.selectedSegmentIndex) {
        case 0:
            breeding = @"yes";
            break;
        case 1:
            breeding = @"no";
            break;
        default:
            break;
    }
    NSString *url = [PPAPIList getAPIList].PPSaveOrUpdatePetMsg;
    NSMutableDictionary *params =[[NSMutableDictionary alloc] initWithDictionary:@{
    @"userId":@(self.config.userInfo.id),
    @"petId":@(self.pet.id),
    @"birth":self.petAgeTF.text,
    @"petName":self.petNameTF.text,
    @"petType":self.petType,
    @"petBreed":self.petBreed,
    @"petGender":@(self.gender),
    @"breeding":breeding,
    @"introduction":self.introductionTextView.text
    }];
    if (self.petLengthTF.text.length > 0) {
        [params setObject:@(self.petLengthTF.text.doubleValue) forKey:@"petLong"];
    }
    if (self.petWeightTF.text.length > 0) {
        [params setObject:@(self.petWeightTF.text.doubleValue) forKey:@"weight"];
    }
    if (self.petColorTF.text.length > 0) {
        [params setObject:self.petColorTF.text forKey:@"color"];
    }
    [httpRequst POST:url parameters:params imagePath:nil imageName:nil keyWords:nil success:^(AFHTTPRequestOperation *operation, id responseObject){
        NSNumber *processResult = responseObject[@"processResult"];
        if (processResult.boolValue) {
            //更新本地宠物信息
            [self.config getPetListwithComepletion:^{
                //发送宠物信息更新通知
                [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshPetInfo" object:nil];
                [self.navigationController popViewControllerAnimated:YES];
            }];
        }else{
            [PPHUD hudShowWithString:@"修改失败" andView:self.view];
        }
        [HUD hideUIBlockingIndicator];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error){
        [HUD hideUIBlockingIndicator];
        [PPHUD hudShowWithString:@"网络不给力" andView:self.view];
    }];
}

- (void)choseMale:(UIButton *)sender {
    self.gender = sender.tag;
    [self.choseMaleButton setImage:[UIImage imageNamed:@"maleBig"] forState:UIControlStateNormal];
    [self.choseFemaleButton setImage:[UIImage imageNamed:@"female"] forState:UIControlStateNormal];
}

- (void)choseFemale:(UIButton *)sender {
    self.gender = sender.tag;
    [self.choseMaleButton setImage:[UIImage imageNamed:@"male"] forState:UIControlStateNormal];
    [self.choseFemaleButton setImage:[UIImage imageNamed:@"femaleBig"] forState:UIControlStateNormal];
}

#pragma mark - UITextFiled delegate

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if ([textField isEqual:self.petAgeTF]) {
        [self.datePicker setDatePickerMode:UIDatePickerModeDate];
        [self.datePicker setMaximumDate:[NSDate date]];
        [self.datePicker setMinimumDate:nil];
        [self.formatter setDateFormat:@"yyyy/MM/dd"];
        NSDate *currentDate;
        if (textField.text.length > 0) {
            if (textField.text.length < 10) {
                currentDate = [NSDate date];
            }else{
                currentDate = [self.formatter dateFromString:self.petAgeTF.text];
            }
        }else{
            currentDate = [NSDate date];
        }
        [self.datePicker setDate:currentDate];
    }
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - UITextView delegate
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    if ([textView isEqual:self.introductionTextView]) {
        self.optionLabel.hidden = YES;
    }
    return YES;
}

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text

{
    if ([text isEqualToString:@"\n"]) {
        if (textView.text.length > 0) {
            self.optionLabel.hidden = YES;
        }else{
            self.optionLabel.hidden = NO;
        }
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
    
    
}

@end
